package com.ocp.socket.busi.jpush.service.impl;

import cn.jpush.api.push.PushResult;
import com.ocp.socket.busi.jpush.bean.PushLog;
import com.ocp.socket.busi.jpush.mapper.JPushLogMapper;
import com.ocp.socket.busi.jpush.service.IJPushService;
import com.ocp.socket.common.Constants;
import com.ocp.socket.common.enums.JPushEnum;
import com.ocp.socket.common.utils.JPushUtil;
import com.ocp.socket.task.bean.WarnMsg;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;

/**
 * @Author : lichong
 * @description :
 * @Date Create in 20:37 2019/5/8
 * @Modified By :
 **/
@Service("jPushService")
public class JPushServiceImpl implements IJPushService {
    @Autowired
    private JPushLogMapper jPushLogMapper;

    /**
     * 推送报警信息，推送对象是orgId的标签对象
     * @param orgId
     * @param busiId
     * @param warnName
     */
    @Override
    @Async
    @Transactional(rollbackFor = Exception.class)
    public void pushWarnMsgWithTags(Integer orgId, String busiId, String warnName) {
        PushLog pushLog = new PushLog(warnName, orgId, JPushEnum.WARN_MSG.getType(), busiId, 0, "tag");
        Long msgId = null;
        Integer status = Constants.PUSH_STATUS_FAIL;
        //保存推送记录
        jPushLogMapper.insertPushLog(pushLog);
        int logId = pushLog.getLogId();
        //保存推送记录的关系
        jPushLogMapper.insertPushLogRel(logId, Arrays.asList(String.valueOf(orgId)));
        //推送信息
        PushResult pushResult = JPushUtil.pushMsgForTags(warnName, JPushEnum.WARN_MSG.getCode(), busiId, logId,String.valueOf(orgId));
        if (pushResult != null && pushResult.getResponseCode() == HttpStatus.SC_OK) {
            status = Constants.PUSH_STATUS_SUCCESS;
            msgId = pushResult.msg_id;
        }
        //修改推送记录
        jPushLogMapper.updatePushLog(logId, status, msgId);
    }

    /**
     * 推送报警信息，推送对象是orgId的标签对象
     * @param warnMsgs
     */
    @Override
    @Async
    public void pushWarnMsgWithTags(List<WarnMsg> warnMsgs) {
        if (CollectionUtils.isEmpty(warnMsgs)) {
            return;
        }
        for (WarnMsg warnMsg : warnMsgs) {
            this.pushWarnMsgWithTags(warnMsg.getOrgId(), warnMsg.getId(), warnMsg.getWarnName());
        }
    }

}
